/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tlf.dyjc5.servlet.point;

import com.tlf.dyjc5.service.ConstantService;
import com.tlf.dyjc5.service.DeviceService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Session;
import org.dusin.commonutil.DateUtil;
import org.dusin.web.util.CommonWebUtil;
import org.dusin.web.util.DeviceCommand;
import org.dusin.web.util.JsonUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author tengyu
 */
public class ParamsSet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String message="";
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();        
        
        List<String> commandList = new ArrayList<String>();
        try {            
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            DeviceService deviceService = (DeviceService) context.getBean("deviceService");
            ConstantService constantService = (ConstantService) context.getBean("constantService");
            String server = constantService.getValue("服务器IP", "01");
            String port = constantService.getValue("服务器端口", "01");
            String command = request.getParameter("cmd");
            //long deviceId  = Long.parseLong(request.getParameter("deviceId"));
            //long deviceId=93;
            //String model = request.getParameter("model");
            String model="dt3";
            int type=0;
            boolean success = true;
            String deviceIdStr = request.getParameter("deviceId");
            //deviceIdStr="93";
            
            
            if("basic1Reader".equals(command)){
                
                commandList.add("DeviceId="+deviceIdStr+"^CMD=GET SXX^");
                Map<String,Object> result = DeviceCommand.excuteCommand(server, port, commandList,type);
                success = (Boolean) (result.get("success"));
                if(success){
                    String responseStr = (String)(result.get("response0"));
                    responseStr = DeviceCommand.deviceResponse2Json(responseStr);
                    message= responseStr;
                }else{
                    message = (String)result.get("message");
                }                
                
            }else if("basic1Set".equals(command)){
                String upperLimit = request.getParameter("upperLimit");
                String  lowerLimit = request.getParameter("lowerLimit");
                String param1 = request.getParameter("param1");
                String param2 = request.getParameter("param2");
                
                /*if(CommonWebUtil.isValidParam(upperLimit)&&CommonWebUtil.isValidParam(lowerLimit)){
                    commandList.add("CMD=SET SXX "+upperLimit+" "+lowerLimit);
                }*/                
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=SET SXX "+param1+upperLimit+lowerLimit+param2+"^"; 
                commandList.add(deviceCommandText);  
                //System.out.println("**********"+deviceCommandText+"********");
            }else if("basic3Reader".equals(command)){
                commandList.add("CMD=GET SERVERADDRESS");
            }else if("basic3Set".equals(command)){
                String appServer = request.getParameter("serverIP");
                String appPort = request.getParameter("serverPort");
                if(CommonWebUtil.isValidParam(appServer)&&CommonWebUtil.isValidParam(appPort)){
                    commandList.add(("CMD=SET SERVERADDRESS "+appServer+" "+appPort));
                }                
            }else if("clock".equals(command)){
                String time = DateUtil.get(new Date(), "yyMMddHHmmss");
                //String deviceIdStr = request.getParameter("deviceId");
                deviceIdStr = "93";                
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=SET TIME "+time+"^"; 
                type=1;
                commandList.add(deviceCommandText);  
                //System.out.println("**********"+deviceCommandText+"********");
            }else if("clockSet".equals(command)){
                String time = request.getParameter("time");
                //String deviceIdStr = request.getParameter("deviceId");
                //deviceIdStr = "93";                
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=SET TIME "+time+"^"; 
                type=1;
                //System.out.println("**********"+deviceCommandText+"********");
                commandList.add(deviceCommandText);                
            }else if("clockRead".equals(command)){
                String time = request.getParameter("time");
                //String deviceIdStr = request.getParameter("deviceId");
                //deviceIdStr = "93";                
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=GET TIME^"; 
                type=0;
                //System.out.println("**********"+deviceCommandText+"********");
                commandList.add(deviceCommandText);                
            }else if("reset".equals(command)){
                //String deviceIdStr = request.getParameter("deviceId");
                //deviceIdStr = "93";                
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=RESET^"; 
                type=1;
                commandList.add(deviceCommandText);
                //System.out.println("**********"+deviceCommandText+"********");
            }else if("rsj".equals(command)){
                String date = request.getParameter("date");
                //String deviceIdStr = request.getParameter("deviceId");
                //deviceIdStr = "93";
                //DeviceID=93^CMD=Get date 0804^
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=Get date "+date+"^"; 
                type=0;
                //System.out.println("**********"+deviceCommandText+"********");
                commandList.add(deviceCommandText);
            } else if("ysj".equals(command)){
                String date = request.getParameter("Month");
                //String deviceIdStr = request.getParameter("deviceId");
                //deviceIdStr = "93";
                //DeviceID=93^CMD=Get Month 07^
                String deviceCommandText = "DeviceId="+deviceIdStr+"^"+"CMD=Get Month "+date+"^"; 
                type=0;
                //System.out.println("**********"+deviceCommandText+"********");
                commandList.add(deviceCommandText);
            }      
                  
            
            Map<String, Object> result = DeviceCommand.excuteCommand(server, port, commandList, type);
            String deviceResponse0 = (String)result.get("response0");
            message = (String)result.get("message");
            success = (Boolean)result.get("success");
            HttpSession session = request.getSession(); //将设备数据保存到session中，以便用保存按钮保存的数据库
            session.setAttribute("response", result);
            success = true;   //测试用，发布时删除改行代码；
            if(success){
                if(type==0){
                    message=DeviceCommand.deviceResponse2Json(deviceResponse0);
                    //测试用，发布时删除改行代码；
                    message = "{TYPE:\"MONTHData\",YEAR:\"2018\",Month:\"11\",Date:\"27\",ZYXS:\"43200\",CSXS:\"3372\",CXXS:\"92\",ZDZ:\"109.7700\",ZDZS:\"11282319\",ZXZ:\"95.5500\",ZXZS:\"11131737\",PJZ:\"104.0200\"}";
                }
               out.println(JsonUtil.createSuccessJsonResponse(message));
            }else{
                 out.print(JsonUtil.createFailureJsonResponse(message));
            }
            out.flush();
        } catch(Exception e){
            out.print(JsonUtil.createFailureJsonResponse(e.getMessage()));
            e.printStackTrace();
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
